<template>
  <div class="position-management">
    <div class="table-header">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索岗位名称"
        style="width: 300px"
        clearable
        @clear="handleSearchClear"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </template>
      </el-input>

      <el-button type="primary" @click="handleAddPosition">
        <el-icon>
          <Plus />
        </el-icon>
        新增岗位要求
      </el-button>
    </div>

    <el-table
      :data="filteredPositions"
      style="width: 100%"
      v-loading="loading"
      stripe
    >
      <el-table-column
        type="index"
        prop="id"
        label="岗位ID"
        width="100"
        align="center"
      />
      <el-table-column
        prop="positionName"
        label="岗位名称"
        width="180"
        align="center"
      />
      <el-table-column
        prop="department"
        label="部门"
        width="120"
        align="center"
      >
        <template #default="scope">
          <el-tag>{{ scope.row.department }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="level" label="职级" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getLevelTag(scope.row.level)">
            {{ scope.row.level }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="requiredEducation"
        label="学历要求"
        width="100"
        align="center"
      />
      <el-table-column
        prop="minWorkYears"
        label="最低工作年限"
        width="120"
        align="center"
      >
        <template #default="scope"> {{ scope.row.minWorkYears }}年 </template>
      </el-table-column>
      <el-table-column
        prop="minPerformanceScore"
        label="最低绩效要求"
        width="120"
        align="center"
      >
        <template #default="scope">
          {{ scope.row.minPerformanceScore }}分
        </template>
      </el-table-column>
      <el-table-column label="能力要求" min-width="200" align="center">
        <template #default="scope">
          <div class="requirement-tags">
            <el-tag
              v-if="scope.row.leadershipRequirement"
              size="small"
              type="success"
            >
              绩效领导力: {{ scope.row.leadershipRequirement }}
            </el-tag>
            <el-tag
              v-if="scope.row.technicalRequirements"
              size="small"
              type="warning"
            >
              技术能力
            </el-tag>
            <el-tag
              v-if="scope.row.communicationRequirements"
              size="small"
              type="info"
            >
              人际交往能力
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="description"
        label="岗位描述"
        show-overflow-tooltip
        align="center"
      />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            link
            @click="
              $emit('edit-position', scope.row);
              handleEditPosition(scope.row);
            "
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            link
            @click="handleDeletePosition(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 岗位要求对话框 -->
    <PositionDialog
      v-model="showPositionDialog"
      :position="editingPosition"
      :mode="positionDialogMode"
      @save="handleSavePosition"
      @close="handleClosePositionDialog"
    />
  </div>
</template>

<script>
import { ref, computed, watch, onMounted } from "vue";
import PositionDialog from "@/components/PositionDialog.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import api from "@/services/api";

export default {
  name: "PositionManagement",
  components: {
    PositionDialog,
  },
  emits: ["add-position", "edit-position", "delete-position"],
  setup() {
    const searchKeyword = ref("");
    const currentPage = ref(1);
    const pageSize = ref(10);
    const loading = ref(false);

    const filteredPositions = ref([]);
    const showPositionDialog = ref(false);
    const editingPosition = ref(null);
    const positionDialogMode = ref("create");

    const handleEditPosition = (position) => {
      editingPosition.value = { ...position };
      positionDialogMode.value = "edit";
      showPositionDialog.value = true;
    };

    // 添加岗位要求
    const handleAddPosition = () => {
      editingPosition.value = null;
      positionDialogMode.value = "create";
      showPositionDialog.value = true;
    };

    const handleDeletePosition = async (position) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除"${position.positionName}"岗位要求吗？`,
          "确认删除",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        await api.deletePosition(position.id);
        await loadData(); // 重新加载数据
        ElMessage.success("岗位要求删除成功");
      } catch (error) {
        if (error !== "cancel") {
          ElMessage.error("删除失败");
        }
      }
    };

    const handleSavePosition = async (positionData) => {
      try {
        if (positionDialogMode.value === "create") {
          await api.createPosition(positionData);
        } else {
          await api.updatePosition(positionData.id, positionData);
        }

        showPositionDialog.value = false;
        await loadData(); // 重新加载数据
        ElMessage.success(
          `岗位要求${
            positionDialogMode.value === "create" ? "创建" : "更新"
          }成功`
        );
      } catch (error) {
        ElMessage.error(
          `岗位要求${
            positionDialogMode.value === "create" ? "创建" : "更新"
          }失败`
        );
      }
    };

    const loadData = async () => {
      try {
        const resPositions = await api.getPositions();
        filteredPositions.value = resPositions.data;
      } catch (error) {
        console.error("加载岗位数据失败:", error);
      }
    };

    const handleClosePositionDialog = () => {
      editingPosition.value = null;
      showPositionDialog.value = false;
    };

    onMounted(async () => {
      try {
        const resPositions = await api.getPositions();
        filteredPositions.value = resPositions.data;
      } catch (error) {
        console.error("加载岗位数据失败:", error);
      }
    });

    const total = computed(() => {
      if (searchKeyword.value) {
        return filteredPositions.value.filter(
          (position) =>
            position.positionName.includes(searchKeyword.value) ||
            position.department.includes(searchKeyword.value)
        ).length;
      }
      return filteredPositions.value.length;
    });

    const getLevelTag = (level) => {
      const levelMap = {
        初级: "info",
        中级: "warning",
        高级: "success",
        专家: "danger",
        管理: "primary",
      };
      return levelMap[level] || "info";
    };

    const handleSearch = async () => {
      currentPage.value = 1;
      if (searchKeyword.value) {
        await api
          .getPositionByName(searchKeyword.value ? searchKeyword.value : "")
          .then((response) => {
            filteredPositions.value = response.data;
          })
          .catch((error) => {
            console.error("搜索岗位失败:", error);
          });
      }
    };

    const handleSearchClear = async () => {
      currentPage.value = 1;
      try {
        const resPositions = await api.getPositions();
        filteredPositions.value = resPositions.data;
      } catch (error) {
        console.error("加载岗位数据失败:", error);
      }
    };

    const handleSizeChange = (newSize) => {
      pageSize.value = newSize;
      currentPage.value = 1;
    };

    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage;
    };

    return {
      searchKeyword,
      currentPage,
      pageSize,
      loading,
      filteredPositions,
      total,
      showPositionDialog,
      editingPosition,
      positionDialogMode,
      handleAddPosition,
      getLevelTag,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      handleSearchClear,
      handleSavePosition,
      handleClosePositionDialog,
      handleEditPosition,
      handleDeletePosition,
    };
  },
};
</script>

<style scoped>
.position-management {
  padding: 20px 0;
}

.table-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.requirement-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}
</style>
